﻿using Application.Common.Interfaces;
using Application.Features.Users.DTOs;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Common.Attributes;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel;

namespace Application.Features.Users.Queries.GetUserMenusByUserId;

/// <summary>
/// 查询用户的菜单
/// </summary>
[Description("查询用户的菜单")]
[GroupDescription(("用户管理"))]
public class GetUserMenusByUserIdQuery : IRequest<IEnumerable<UserMenuOutput>>
{
    /// <summary>
    /// 用户唯一标识
    /// </summary>
    public long UserId { get; set; }
}

public class GetUserMenusByUserIdQueryHandler :
    IRequestHandler<GetUserMenusByUserIdQuery, IEnumerable<UserMenuOutput>>
{
    private readonly IApplicationDbContext _context;
    private readonly IMapper _mapper;

    public GetUserMenusByUserIdQueryHandler(
        IApplicationDbContext context,
        IMapper mapper
    )
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<IEnumerable<UserMenuOutput>> Handle(GetUserMenusByUserIdQuery request, CancellationToken cancellationToken)
    {
        var userMenus = await _context.Menus
            .Include(m => m.Meta)
            .Include(rm => rm.RoleMenus)
                .ThenInclude(r => r.Role)
                    .ThenInclude(ru => ru.UserRoles)
            .Where(menu => menu.RoleMenus.Any(rm => rm.Role.UserRoles.Any(ur => ur.UserId == request.UserId)))
            .ProjectTo<UserMenuOutput>(_mapper.ConfigurationProvider)
            .ToListAsync(cancellationToken);

        return userMenus;
    }
}